<template>
  <div class="app-container, dashboard-container" v-loading="loading">
    <el-card class="tree-card">
      <!-- 头部的tree-tools -->
      <tree-tools
        :tree-node="company"
        :is-root="true"
        @addDepts="addChildDepartment"
      />

      <!-- //在el-card内部最底部添加tree -->
      <el-tree :data="departs" :props="defaultProps" default-expand-all>
        <template v-slot="{ data }">
          <treeTools
            :treeNode="data"
            @delDepartments="getDepartments"
            @addDepts="addChildDepartment"
            @redactDepartment="redactDepartment"
          >
          </treeTools>
        </template>
      </el-tree>
    </el-card>

    <addDept
      ref="addDept"
      :showDialog="showDialog"
      :treeNode="treeNode"
      @addDepts="getDepartments"
      :show-dialog.sync="showDialog"
    >
    </addDept>
  </div>
</template>

<script>
import treeTools from "./components/tree-tools.vue";
import { getDepartmentsAPI } from "@/api/departments";
import { tranListToTreeData } from "@/utils";
import addDept from "./components/add-dept.vue";
export default {
  data() {
    return {
      departs: [],
      defaultProps: {
        label: "name", // 表示 从这个属性显示内容
      },
      // 头部treeTools数据
      company: {},
      // 是否显示弹出框
      showDialog: false,
      // 当前新增部门的信息
      treeNode: null,
      loading: false, // 用来控制进度弹层的显示和隐藏
    };
  },
  components: {
    treeTools,
    addDept,
  },
  created() {
    this.getDepartments();
  },
  methods: {
    // 获取树结构
    async getDepartments() {
      this.loading = true; //获取前，改为true
      // 获取树形结构数据
      let result = await getDepartmentsAPI();
      this.company = { name: result.companyName, manager: "负责人", id: "" };
      // 这里定义一个空串  因为 它是根 所有的子节点的数据pid 都是 ""
      this.departs = tranListToTreeData(result.depts, "");
      this.loading = false; //获取后，改为false
    },
    // 添加子部门回调
    addChildDepartment(treeNode) {
      this.showDialog = true;
      this.treeNode = treeNode;
    },
    // 编辑部门回调
    redactDepartment(node) {
      this.showDialog = true;
      this.treeNode = node;
      // 在这里直接调用子组件的回调传递当前编辑部门id
      let { addDept } = this.$refs;
      addDept.queryDepartmentInfo(node.id);
    },
  },
};
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>